<template lang="pug">
el-upload(
  class="avatar-uploader"
  :http-request="httpRequest"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload")
  img(v-if="imageUrl" :src="imageUrl" class="avatar")
  mt-icon(v-else, name="Plus", class="avatar-uploader-icon"
  accept=".jpg, .jpeg, .png, .gif"
  :loading="loadingMap['metadataUpload']"
)

</template>

<script setup lang="ts">
import {
  useNotify
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { useApi } from "@scmt/core-api";

//添加 Props属性
const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
});
const emit = defineEmits(["model-value-update"]);
const $notify = useNotify();
const imageUrl = ref("");
const $api = useApi();
const { request, data, loadingMap } = useRequest({
  metadataUpload: (entity: any) => {
    return $api.fileUpload.metadataUpload(entity);
  },
});

const handleAvatarSuccess = (res: any, file: any) => {
  if (res && file) {
    imageUrl.value = URL.createObjectURL(file.raw);
  }

};
const beforeAvatarUpload = (file: any) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
  const isAllowed = allowedTypes.includes(file.type);
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isAllowed) {
    $notify.error('只能上传 JPG/PNG/GIF 格式的图片!');
  }
  if (!isLt5M) {
    $notify.error('上传头像图片大小不能超过 5MB!');
  }
  return isLt5M;
}
const httpRequest = (data: any) => {

  if (data && data.file) {
    const reader = new FileReader(); // 创建FileReader实例

    reader.onload = function (loadEvent: ProgressEvent) {
      //@ts-ignore
      const base64Data = loadEvent.target?.result;
      console.log(base64Data);
      if (base64Data) {
        // 调用回调函数并传递Base64字符串
        handleBase64Data(base64Data, data.file.name);
      }

    };

    reader.onerror = function (error) {
      console.error('Error: ', error);
    };

    reader.readAsDataURL(data.file); // 读取文件并转换为Base64
  }
}
// 调用回调函数并传递Base64字符串
const handleBase64Data = (base64: string, fileName: string) => {
  if (base64) {
    base64 = base64.split(',')[1]
  }
  const entity = $api.fileUpload.$$createEntity({ metadataName: fileName, metadataContent: base64 })
  request("metadataUpload", entity).then(() => {
    const res = data.metadataUpload ?? null
    if (res && res.fileUrl) {
      imageUrl.value = res.fileUrl;
      emit("model-value-update", imageUrl.value)
    }
  })
}
watch(
  () => props.modelValue,
  (value) => {
    if (value) {
      imageUrl.value = value;
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less">
.avatar-uploader {

  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }

  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
}
</style>
